<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
	</head>
	<body>
		<canvas id="mycanvas" width="600px" height="600px" style="border: 1px solid grey;"></canvas>
		<script type="text/javascript">
			const mycanvas = document.getElementById('mycanvas');
			const ctx = mycanvas.getContext('2d');
			
			var token = null;
			
			var ball = {
				posx: 300,
				posy: 300,
				vx: 5,
				vy: 5,
				run: false,
				draw: () => {
					console.log(ball.vx , ball.vy);
					ctx.beginPath();
					ctx.arc(ball.posx , ball.posy , 20 , 0 , Math.PI * 2 , true);
					ctx.closePath();
					ctx.fillStyle = "blue";
					ctx.fill();
				}
			}
			
			function clear() {
				ctx.fillStyle = 'rgba(255 , 255 , 255 , 0.3)';
				ctx.fillRect(0 , 0 , mycanvas.height , mycanvas.width);
			}
			
			function draw() {
				clear();
				if(ball.run) {
					ball.posx += ball.vx;
					ball.posy += ball.vy;
					if(ball.posx > mycanvas.width || ball.posx < 0) {
						ball.vx = -ball.vx;
					}
					if(ball.posy > mycanvas.height || ball.posy < 0) {
						ball.vy = -ball.vy;
					}
				}
				ball.draw();
				token = window.requestAnimationFrame(draw);
			}
			
			mycanvas.addEventListener("mousemove" , (event) => {
				if(ball.run) {
					cancelAnimationFrame(token);
				}
				clear();
				ball.draw();
				ball.posx = event.offsetX;
				ball.posy = event.offsetY;
			})
			
			mycanvas.addEventListener('click' , () => {
				if(ball.run) {
					cancelAnimationFrame(token);
				}
				ball.run = true;
				token = window.requestAnimationFrame(draw);
			})
			draw();
		</script>
	</body>
</html>
